#include "password.h"

//********************************************************************************
//随机生成盐值
//********************************************************************************
void get_salt(char *salt)
{
    char str[STR_LEN + 5] = {0}; //$6...$\0
    //$6$QTMje.pRHnM2UEQ8$
    str[0] = '$';
    str[1] = '6';
    str[2] = '$';
    int i, flag;
    srand(time(NULL));
    for (i = 0; i < STR_LEN; i++)
    {
        flag = rand() % 3;
        switch (flag)
        {
        case 0:
            str[i + 3] = rand() % 26 + 'a';
        case 1:
            str[i + 3] = rand() % 26 + 'A';
        case 2:
            str[i + 3] = rand() % 10 + '0';
        }
    }
    str[i + 3] = '$';
    strcpy(salt, str);
}

//********************************************************************************
//给客户端发送盐值，让客户端本地加密
//********************************************************************************
void sendSaltToClient(int peerfd, char *salt)
{
    //先发长度
    train_t train;
    train.len = strlen(salt);
    strcpy(train.data, salt);
    send(peerfd, &train, train.len + 4, MSG_WAITALL);
}

//********************************************************************************
//用户登录
//********************************************************************************
int loginServer(int peerfd, char *username)
{
    // 1.接收用户名
    //printf("username = %s\n", username);
    // 2.验证是否已有用户
    int exit = 200;
    if (Exituser(username) != -1)
    { //不存在发送404
        printf("username exits!\n");
        exit = 404;
        send(peerfd, &exit, 4, MSG_WAITALL);
        return -1;
    }
    send(peerfd, &exit, 4, MSG_WAITALL);
    // 2.1查询盐值
    char *que = "select salt from user where username =";
    char query[1024] = {0};
    sprintf(query, "%s \"%s\"", que, username);
    OPEN_MYSQL(myconnect);
    int flag = 0;
    mysql_query(&myconnect, query);
    // 2.2发送盐值
    MYSQL_RES *result = mysql_store_result(&myconnect);
    MYSQL_ROW row = mysql_fetch_row(result);
    sendMsg(peerfd, row[0]);

    mysql_free_result(result);
    // 3.接收密文
    int lenOfPasswd = 0;
    int retval = recv(peerfd, &lenOfPasswd, 4, MSG_WAITALL);
    if (retval == 0)
        return -1;

    char passwd[200] = {0};
    retval = recv(peerfd, passwd, lenOfPasswd, MSG_WAITALL);
    if (retval == 0)
        return -1;

    // 4.验证密文正确性
    que = "select cryptpasswd from user where username = ";
    memset(&query, 0, 200);
    sprintf(query, "%s \"%s\"", que, username);
    mysql_query(&myconnect, query);
    MYSQL_RES *passwordResule = mysql_store_result(&myconnect);
    MYSQL_ROW passwordRow = mysql_fetch_row(passwordResule);
    if (strcmp(passwd, passwordRow[0]) == 0)
    {
        flag = 200;
        send(peerfd, &flag, 4, MSG_WAITALL);
    }
    else
    {
        flag = 404;
        send(peerfd, &flag, 4, MSG_WAITALL);
    }
    mysql_free_result(passwordResule);
    CLOSE_MYSQL(myconnect);

    return 0;
}

//********************************************************************************
//用户注册
//********************************************************************************
int userRegister(int peerfd, char *username)
{
    // 1.接收用户名
    // 1.2判断用户名是否存在
    int exit = 200;
    if (Exituser(username) == -1)
    { //存在发送404表示错误
        printf("username exits!\n");
        exit = 404;
        send(peerfd, &exit, 4, MSG_WAITALL);
        return -1;
    }
    send(peerfd, &exit, 4, MSG_WAITALL);

    // 2.生成随机盐值发送
    char salt[25] = {0};
    get_salt(salt);
    sendSaltToClient(peerfd, salt);

    // 3.接收密文
    char passwd[200] = {0};
    int paaawdlength = 0;
    int retval = recvCircle(peerfd, (char *)&paaawdlength, 4);
    if(retval != 4)
        return -1;
    retval = recvCircle(peerfd, passwd, paaawdlength);
    if(retval != 4)
        return -1;

    // 4.插入数据库
    OPEN_MYSQL(myconnect);
    char *query = "insert into user(username,salt,cryptpasswd,pwd) values ";
    char sqlarray[1024] = {0};
    sprintf(sqlarray, "%s (\"%s\",\"%s\",\"%s\",\"usr/%s\")", query, username, salt, passwd, username);
    printf("sqlarray = %s\n", sqlarray);
    mysql_query(&myconnect, sqlarray);
    CLOSE_MYSQL(myconnect);

    OPEN_MYSQL(myconnect);
    //插入虚拟文件表
    //取userid
    char *query = "SELECT id FROM user WHERE username = ";
    char sqlarray[1024] = {0};
    sprintf(sqlarray, "%s\"%s\"", query, username);
    printf("sqlarray = %s\n", sqlarray);
    mysql_query(&myconnect, sqlarray);
    MYSQL_RES *result = mysql_store_result(&myconnect);
    MYSQL_ROW row = mysql_fetch_row(result);
    int usrid = atoi(row[0]);
    mysql_free_result(result);
    //插入虚拟文件表
    query = "INSERT INTO virtualfile(parent_id,filename,owner_id,md5,type) values";
    sprintf(sqlarray, "%s (%d,\"%s\",%d,\"%s\",%d)", query, 0, username, usrid, "0", 1);

    mysql_query(&myconnect, sqlarray);
    CLOSE_MYSQL(myconnect);
}

int Exituser(char *username)
{
    int flags = 0;
    OPEN_MYSQL(myconnect);
    char *query1 = "select username from user where username=";
    char sqlarray[200] = {0};
    sprintf(sqlarray, "%s\"%s\"", query1, username);
    int ret = mysql_query(&myconnect, sqlarray);
    MYSQL_RES *result = mysql_store_result(&myconnect);
    MYSQL_ROW row = mysql_fetch_row(result);
    if (row != NULL)
    { //存在
        flags = -1;
    }
    mysql_free_result(result);
    CLOSE_MYSQL(myconnect);
    return flags;
}